package dht.server;

import java.util.LinkedList;
import java.util.Queue;

import dht.IServer;
import dht.entity.NodeInfo;
import dht.socket.SocketHandler;
import dht.socket.TcpConnection;
import dht.throwable.DhtException;

public abstract class AbstractServer implements IServer {

	protected NodeInfo localInfo;
	protected Queue<SocketHandler> socketQueue;
	protected TcpConnection tcpConnection;

	public AbstractServer(NodeInfo localInfo) {
		this.localInfo = localInfo;
		this.socketQueue = new LinkedList<SocketHandler>();
		this.tcpConnection = new TcpConnection(this.localInfo, socketQueue);
	}

	@Override
	public void run() {
		try {
			tcpConnection.runServerSocket(localInfo.getPort());
		} catch (DhtException e) {
			e.printStackTrace();
		}

		while (true) {
			synchronized (socketQueue) {
				while (!socketQueue.isEmpty()) {
					SocketHandler socketHandler = socketQueue.poll();
					try {
						handlePassiveTransaction(socketHandler, false);
					} catch (DhtException e) {
						e.printStackTrace();
					}
				}
				try {
					socketQueue.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public NodeInfo getLocalInfo() {
		return localInfo;
	}

}
